const { joinTask, taskDetail, quitTask, getTaskMemberPage } = require('../../../utils/task');
const { formatDateTime, formatDateTimeNoSeconds, formatyyyyMMdd } = require('../../../utils/date');

// 顶部banner的top距离
const bannerTop = -52;

Page({
  data: {
    countdown: '',
    cycleRule: '每天中午12点到14点',
    clockTime: '下午19点到晚上22点',
    quoteCount: 123,
    joined: false,
    ended: false,
    showJoinBtn: true,
    joinBtnClass: '',
    joinBtnText: '加入',
    joinBtnDisabled: false,
    members: [],
    current: 1,
    size: 12,
    memberHasMore: true,
    memberLoading: false,
    mainTop: bannerTop,
    mainTopTransition: '',
    // 允许中途退出
    quitMidwayFlag: '',
    taskId: '',
    taskDetail: {}
  },
  async onLoad(options) {
    this.setData({ taskId: options.id });
    try {
      const detail = await taskDetail(options.id);
      // 格式化时间
      detail.startTimeFmt = formatDateTime(detail.taskStartTime);
      detail.endTimeFmt = formatDateTime(detail.taskEndTime);
      detail.joinTimeFmt = formatDateTimeNoSeconds(detail.joinTime);
      this.setData({taskDetail: detail});
      this.updateCountdown();
      // 初始加载成员
      this.loadInitialMembers();
      this.countdownTimer = setInterval(() => this.updateCountdown(), 1000);
    } catch (e) {
      console.log(e);
      wx.showToast({ 
        title: e.data.msg || '获取任务详情失败', 
        icon: 'none',
        duration: 1500,
        complete: () => {
          // 延迟返回，让用户看到错误提示
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        }
      });
    }
  },
  onUnload() {
    if (this.countdownTimer) clearInterval(this.countdownTimer);
  },
  updateCountdown() {
    const endStr = this.data.taskDetail.taskEndTime;
    if (!endStr) {
      if (this.data.countdown !== '无结束时间' || this.data.ended !== false) {
        this.setData({ countdown: '无结束时间', ended: false });
      }
      return;
    }
    const end = new Date(endStr).getTime();
    const now = Date.now();
    if (isNaN(end)) {
      if (this.data.countdown !== '时间格式错误' || this.data.ended !== false) {
        this.setData({ countdown: '时间格式错误', ended: false });
      }
      return;
    }
    let diff = Math.floor((end - now) / 1000);
    if (diff <= 0) {
      if (this.data.countdown !== '已结束' || this.data.ended !== true || this.data.showJoinBtn !== this.data.taskDetail.joined) {
        this.setData({
          countdown: '已结束',
          ended: true,
          showJoinBtn: this.data.taskDetail.joined,
        });
      }
      if (this.countdownTimer) clearInterval(this.countdownTimer);
      return;
    }
    const d = Math.floor(diff / 86400);
    diff %= 86400;
    const h = Math.floor(diff / 3600);
    diff %= 3600;
    const m = Math.floor(diff / 60);
    const s = diff % 60;
    let str = '';
    if (d > 0) str += `${d}天`;
    if (h > 0) str += `${h}小时`;
    if (m > 0) str += `${m}分`;
    str += `${s}秒后结束`;
    if (this.data.countdown !== str || this.data.ended !== false || this.data.showJoinBtn !== true) {
      this.setData({
        countdown: str,
        ended: false,
        showJoinBtn: true
      });
    }
  },
  onJoin() {
    if (this.data.taskDetail.joined || this.data.ended) return;
    const taskId = this.data.taskDetail.id;
    if(this.data.taskDetail.quitMidwayFlag !== 'yes') {
      wx.showModal({
        title: '加入任务提醒',
        content: '该任务禁止中途退出，确定还要加入任务吗？',
        confirmText: '退出',
        cancelText: '取消',
        success: (res) => {
          this.submitJoinTask(taskId);
        }
      });
    } else{
      this.submitJoinTask(taskId);
    }
  },
  /**
   *  提交加入任务
   * @param {*} taskId 
   */
  submitJoinTask(taskId) {
    joinTask(this.data.taskId).then(async () => {
      // 重新获取任务详情
      await this.commonLoadTaskDetail();
      wx.showToast({ title: '已加入', icon: 'success' });
      this.updateCountdown();
    }).catch(() => {
      wx.showToast({ title: '加入失败', icon: 'none' });
    });
  },    
  // 初始加载成员
  async loadInitialMembers() {
    try {
      const { size, current, taskId } = this.data;
      const res = await getTaskMemberPage(
        taskId,
        current,
        size
      );
      
      if (res && res.records) {
        // 对加入时间进行格式化
        res.records.forEach(userTask => {
          userTask.joinTime = formatyyyyMMdd(userTask.joinTime);
        });
        this.setData({
          members: res.records,
          current: current + 1,
          memberHasMore: res.records.length >= size
        });
      }
    } catch (e) {
      console.error('加载成员列表失败:', e);
      wx.showToast({ title: '加载成员列表失败', icon: 'none' });
    }
  },
  async loadMembers() {
    if (!this.data.memberHasMore || this.data.memberLoading) return;
    
    this.setData({ memberLoading: true });
    try {
      const { current, size, members } = this.data;
      const res = await getTaskMemberPage(
        this.data.taskId,
        current,
        size
      );

      if (res && res.records) {
        // 对加入时间进行格式化
        res.records.forEach(userTask => {
          userTask.joinTime = formatyyyyMMdd(userTask.joinTime);
        });
        this.setData({
          members: members.concat(res.records),
          current: current + 1,
          memberHasMore: res.records.length >= size,
          memberLoading: false
        });
      } else {
        this.setData({
          memberHasMore: false,
          memberLoading: false
        });
      }
    } catch (e) {
      console.error('加载更多成员失败:', e);
      this.setData({ memberLoading: false });
      wx.showToast({ title: '加载更多成员失败', icon: 'none' });
    }
  },
  onMemberScrollToLower(e) {
    // 只在滚动到底部时加载下一页
    if (!this.data.memberHasMore || this.data.memberLoading) return;
    this.loadMembers();
  },
  onMemberScroll(e) {
    // e.detail.scrollTop
    const scrollTop = e.detail.scrollTop;
    // top: -52rpx ~ 0
    let top = bannerTop + scrollTop;
    if (top > 0) top = 0;
    if (top < bannerTop) top = bannerTop;
    this.setData({
      mainTop: top,
      mainTopTransition: 'top 0.2s cubic-bezier(0.4,0,0.2,1)' // 动画
    });
  },
  onQuitJoin() {
    wx.showModal({
      title: '退出任务',
      content: '确定要退出该任务吗？',
      confirmText: '退出',
      cancelText: '取消',
      success: async (res) => {
        if (res.confirm) {
          try {
            await quitTask(this.data.taskId);
            await this.commonLoadTaskDetail();
            wx.showToast({ title: '已退出任务', icon: 'success' });
          } catch (res) {
            var msg = res.data ? res.data.msg : '';
            wx.showToast({ title: '退出失败: '+ msg, icon: 'none' });
          }
        }
      }
    });
  },
  navigateToMyCheckIn() {
    wx.navigateTo({
      url: '/pages/task/my-check-in/my-check-in'
    });
  },
  navigateToTaskStatistics() {
    wx.navigateTo({
      url: `/pages/task/task-statistics/task-statistics?taskId=${this.data.taskId}`
    });
  },
  /**
   * 公共方法，重新获取任务详情
   */
  async commonLoadTaskDetail() {
    // 重新获取任务详情
    const detail = await taskDetail(this.data.taskId);
    detail.startTimeFmt = formatDateTime(detail.taskStartTime);
    detail.endTimeFmt = formatDateTime(detail.taskEndTime);
    detail.joinTimeFmt = formatDateTimeNoSeconds(detail.joinTime);
    this.setData({
      taskDetail: detail
    });
  }
}); 